package com.yiwei.zxp.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.SureOrderExpandAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.AddressAddBean;
import com.yiwei.zxp.api.bean.BuyListBean;
import com.yiwei.zxp.api.bean.GoodsBuyOrderBean;
import com.yiwei.zxp.api.bean.GoodsPayBean;
import com.yiwei.zxp.api.bean.PassVerifyBean;
import com.yiwei.zxp.api.model.BuyListModel;
import com.yiwei.zxp.api.model.GoodsBuyOrderModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.AddAddressEvent;
import com.yiwei.zxp.event.ChangeAddressEvent;
import com.yiwei.zxp.event.ShopCartEvent;
import com.yiwei.zxp.util.Arith;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.MD5;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.NestedExpandaleListView;
import com.yiwei.zxp.view.SecurityPassDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class SureOrderActivity extends BaseActivity implements SureOrderExpandAdapter.OnChooseListener {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.layout_address_empty)
    FrameLayout layoutAddressEmpty;
    @BindView(R.id.txt_name_phone)
    TextView txtNamePhone;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.layout_address_data)
    FrameLayout layoutAddressData;
    @BindView(R.id.txt_left_info)
    TextView txtLeftInfo;
    @BindView(R.id.txt_right_info)
    TextView txtRightInfo;
    @BindView(R.id.txt_true_money)
    TextView txtTrueMoney;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.expandableListView)
    NestedExpandaleListView expandableListView;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;

    private Unbinder unbiner;
    private int x24;
    private SureOrderExpandAdapter adapter;
    private GoodsBuyOrderBean submitBean;
    private String address_id = "";
    private double canUseMoney;
    private double orderTotalMoney = 0;
    private int total_num;
    private double total_deliver_fee;
    private double[] shareItems;
    private double share_gold;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sure_order);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        canUseMoney = Float.valueOf(UserInfoGlobal.getTTB());

        submitBean = new GoodsBuyOrderBean();
        txtTitle.setText("确认订单");
        x24 = getResources().getDimensionPixelSize(R.dimen.x24);
        Spanned txtLeft = Spans.with(this).font("商品数量\n", x24, 0xff000000).
                font("商品总价\n", x24, 0xff000000).
                font("淘淘币抵扣\n", x24, 0xff000000).
                font("运费", x24, 0xff000000).
                build();
        txtLeftInfo.setText(txtLeft);

        BuyListBean data = getIntent().getParcelableExtra("data");
        if (data != null) {
            getSureOrder(data);
        }
        getAddressList();
        getUser();
    }

    public void getUser() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        Api.api_service.getUserInfo().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        UserInfoGlobal.saveUserInfo(result.datas);
                        canUseMoney = Float.valueOf(result.datas.balance);
                    }
                });
    }


    //    验证交易密码
    public void getPassVerify(String pass) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        PassVerifyBean bean = new PassVerifyBean();
        bean.password = MD5.getMD5str(pass);
        Api.api_service.getPassVerify(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    getGoodBuySubmitOrder(submitBean);
                });
    }

    //    获取确认的订单
    public void getSureOrder(BuyListBean bean) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getBuyLists(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setOrderData(result.datas);
                });
    }

    //    提交订单
    public void getGoodBuySubmitOrder(GoodsBuyOrderBean bean) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getGoodBuySubmitOrder(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new ShopCartEvent());
                    ToastUtil.makeText(this, "创建订单成功");
                    ArrayList<String> order_no = new ArrayList<>();
                    for (int i = 0; i < result.datas.orders_no.size(); i++) {
                        if (result.datas.orders_no.get(i).is_pay == 0) {
                            order_no.add(result.datas.orders_no.get(i).order_no);
                        }
                    }
                    if (order_no.size() == 0) {
//                        全部已付款
                        Util.startActivity(this, PaySuccessActivity.class);
                        finish();
                    } else {
                        Intent intent = new Intent(this, PayTypeActivity.class);
                        intent.putStringArrayListExtra("data", order_no);
                        startActivity(intent);
                        finish();
                    }

                });
    }


    public void getAddressList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getAddressLists().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas == null || result.datas.size() == 0) {
                        layoutAddressEmpty.setVisibility(View.VISIBLE);
                        layoutAddressData.setVisibility(View.GONE);
                    } else {
                        layoutAddressEmpty.setVisibility(View.GONE);
                        layoutAddressData.setVisibility(View.VISIBLE);

                        if (result.datas.size() == 1) {
                            address_id = result.datas.get(0).id;
                            txtNamePhone.setText(result.datas.get(0).name + "     " + result.datas.get(0).phone);
                            txtAddress.setText(result.datas.get(0).headAddress + result.datas.get(0).address);
                            return;
                        }
                        for (int i = 0; i < result.datas.size(); i++) {
                            if (result.datas.get(i).is_default == 1) {
                                //                        设置默认收货地址

                                address_id = result.datas.get(i).id;
                                txtNamePhone.setText(result.datas.get(i).name + "     " + result.datas.get(i).phone);
                                txtAddress.setText(result.datas.get(i).headAddress + result.datas.get(i).address);
                            }
                        }
                    }

                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddressAddBean event) {
        getAddressList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ChangeAddressEvent event) {
        //                        修改收货地址
        layoutAddressEmpty.setVisibility(View.GONE);
        layoutAddressData.setVisibility(View.VISIBLE);
        address_id = event.data.id;
        txtNamePhone.setText(event.data.name + "     " + event.data.phone);
        txtAddress.setText(event.data.headAddress + event.data.address);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddAddressEvent event) {
        getAddressList();
    }


    private void setOrderData(List<BuyListModel.DatasBean> datas) {
        adapter = new SureOrderExpandAdapter(this, datas);
        adapter.setOnChooseListener(this);
        expandableListView.setAdapter(adapter);
        //展开所有的分组
        for (int i = 0; i < datas.size(); i++) {
            expandableListView.expandGroup(i);
        }

        submitBean.items = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            GoodsBuyOrderBean.ItemsBean beam = new GoodsBuyOrderBean.ItemsBean();
            beam.goods = new ArrayList<>();
            beam.shop_id = datas.get(i).shop_info.shop_id;
            beam.use_shared_gold = 0;
            shareItems = new double[datas.size()];
//            beam.address_id = address_id;
            for (int j = 0; j < datas.get(i).items.size(); j++) {
                BuyListModel.DatasBean.ItemsBean itemData = datas.get(i).items.get(j);
                int num = itemData.num;
//                总价钱
//                orderTotalMoney += num * Float.valueOf(itemData.price);
                orderTotalMoney = Arith.add(orderTotalMoney, Arith.mul(num, Double.valueOf(itemData.price)));
//                总数量
                total_num += num;
//                总运费
//                total_deliver_fee += Float.valueOf(itemData.deliver_fee);
                total_deliver_fee = Arith.add(total_deliver_fee, Double.valueOf(itemData.deliver_fee));

                GoodsBuyOrderBean.ItemsBean.GoodsBean itemBean = new GoodsBuyOrderBean.ItemsBean.GoodsBean();
                itemBean.goods_no = itemData.goods_no;
                itemBean.num = itemData.num;
                beam.goods.add(itemBean);
            }
            submitBean.items.add(beam);
        }

        Spanned txtRight = Spans.with(this).font(total_num + "\n", x24, 0xff000000).style(Typeface.BOLD).
                font("￥" + orderTotalMoney, x24, 0xffFF0030).style(Typeface.BOLD).
                font("\n-￥0.00", x24, 0xffFF0030).style(Typeface.BOLD).
                font("\n+￥" + total_deliver_fee, x24, 0xffFF0030).style(Typeface.BOLD).
                build();
        txtRightInfo.setText(txtRight);

//        txtTrueMoney.setText("￥" + (orderTotalMoney + total_deliver_fee));
        txtTrueMoney.setText("￥" + Arith.add(orderTotalMoney, total_deliver_fee));

        txtMoney.setText(Arith.add(orderTotalMoney, total_deliver_fee) + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.layout_address_data, R.id.btn_back, R.id.layout_address_empty, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.layout_address_data:
                Intent intent = new Intent(this, MyAddressActivity.class);
                intent.putExtra("is_select", true);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.layout_address_empty:
                Intent intent1 = new Intent(this, AddressEditActivity.class);
                intent1.putExtra("is_select", true);
                startActivity(intent1);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_submit:
                if (submitBean == null) {
                    return;
                }
                if (TextUtils.isEmpty(address_id)) {
                    ToastUtil.makeText(this, "地址不能为空");
                    return;
                }
                if (submitBean.items == null || submitBean.items.size() == 0) {
                    return;
                }

//                查看是否设置交易密码
                if (!UserInfoGlobal.getIssetPayPass()) {
                    Dialog.showDefaultDialog(this, "", "为了您的交易安全，请设置交易密码", "", "立即设置", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            Util.startActivity(SureOrderActivity.this, AccountSecurityActivity.class);
                        }

                        @Override
                        public void cancel() {

                        }
                    });

                    return;
                }
                for (int i = 0; i < submitBean.items.size(); i++) {
                    submitBean.items.get(i).address_id = address_id;
                }

                for (int i = 0; i < submitBean.items.size(); i++) {
                    if (submitBean.items.get(i).use_shared_gold == 1) {
                        new SecurityPassDilaog(this).setOnChooseListener(new SecurityPassDilaog.OnChooseListener() {
                            @Override
                            public void onCustomParamChoose(String pass) {
                                getPassVerify(pass);
                            }
                        }).
                                setOrderMoney(share_gold + "").
                                show();
                        return;
                    }
                    break;
                }
                getGoodBuySubmitOrder(submitBean);
                break;
        }
    }

    @Override
    public void onClick(int poi, boolean is_use, float money) {
        if (is_use) {
            submitBean.items.get(poi).use_shared_gold = 1;
            if (canUseMoney >= money) {
                shareItems[poi] = money;
//                canUseMoney -= money;
                canUseMoney = Arith.sub(canUseMoney, money);
            } else {

                if (canUseMoney == 0) {
                    shareItems[poi] = 0;
                } else {
                    shareItems[poi] = canUseMoney;
                    canUseMoney = 0;
                }
            }
        } else {
            submitBean.items.get(poi).use_shared_gold = 0;
//            canUseMoney += shareItems[poi];
            canUseMoney = Arith.add(canUseMoney, shareItems[poi]);
            shareItems[poi] = 0;
        }

        share_gold = 0;
        for (int i = 0; i < shareItems.length; i++) {
//            share_gold += shareItems[i];
            share_gold = Arith.add(share_gold, shareItems[i]);
        }
        Spanned txtRight = Spans.with(this).font(total_num + "\n", x24, 0xff000000).style(Typeface.BOLD).
                font("￥" + orderTotalMoney, x24, 0xffFF0030).style(Typeface.BOLD).
                font("\n-￥" + share_gold, x24, 0xffFF0030).style(Typeface.BOLD).
                font("\n+￥" + total_deliver_fee, x24, 0xffFF0030).style(Typeface.BOLD).
                build();
        txtRightInfo.setText(txtRight);
//        txtTrueMoney.setText("￥" + (orderTotalMoney + total_deliver_fee - share_gold));
        txtTrueMoney.setText("￥" + Arith.sub(Arith.add(orderTotalMoney, total_deliver_fee), share_gold));


//        txtMoney.setText((orderTotalMoney + total_deliver_fee - share_gold) + "");
        txtMoney.setText(Arith.sub(Arith.add(orderTotalMoney, total_deliver_fee), share_gold) + "");
    }
}
